<template>
  <router-view />
</template>

<script setup lang="ts">
import { onMounted, ref, getCurrentInstance, reactive } from "vue";
import indexedDBStore from "@/store/module/indexedDB";
import addressBookStore from "@/store/module/addressBook";
import { addData } from "@/utils/utils.ts";
import { sendNotification } from "@/utils/notification.ts";
import chatListStore from "@/store/module/chatList";

let db = indexedDBStore();
let addressBook = addressBookStore();
let chatList = chatListStore();
const initDB = () => {
  db.setDb().then((res) => {
    db.indexedDB = res;
  });
};
let global = getCurrentInstance()?.appContext.config.globalProperties.$global;
let timer = null;
const userInfo = JSON.parse(localStorage.getItem("userInfo"));
onMounted(() => {
  if (userInfo) {
    setTimeout(() => {
      initDB();
      initWs();
    }, 1);
  }
});
const initWs = () => {
  const ws = new WebSocket("ws://192.168.10.23:5000/chat");
  global.setWs(ws);
  ws.onopen = () => {
    console.log("连接成功");
    ws.send(
      JSON.stringify({
        type: "login",
        id: userInfo.uid,
      })
    );
    timer = setInterval(() => {
      ws.send(
        JSON.stringify({
          type: "heartbeat",
          msg: "ping",
        })
      );
    }, 10000);
  };
  ws.onmessage = (e) => {
    const data = JSON.parse(e.data);
    console.log(data);
    if (data.type === "notice") {
      if (data.msgType === "friendRequest") {
        addressBook.addUnReadCount(data.data);
        addressBook.updateAddFriendList(data.data);
      }
    } else {
      if (data.type === "message" && data.from.id !== userInfo.uid) {
        sendNotification(`${data.from.name}：${data.msg}`, data.from.avatar);
      } else if (data.url && data.from.id !== userInfo.uid) {
        sendNotification(`${data.from.name}：图片`, data.from.avatar);
      }
      db.unReadCount++;
      localStorage.setItem("unReadCount", String(db.unReadCount));
      chatList.addChat(data);
      addData(db.indexedDB, "messages", data);
    }
  };
  ws.onclose = () => {
    console.log("Connection closed");
    clearInterval(timer);
    timer = null;
    initWs();
    setTimeout(() => {
      window.location.reload();
    }, 100);
  };
};
</script>

<style scoped></style>
